import sys
import os
import cgi

try:
	import config
	import database
	import viewer
	import controller
except:
	print "Can't load modules"

__listModel =['home','about','help','post','view','preview','delete']
__model= {}

def __loadModels():

	modelLocation = [sys.path[0]+'/model']
	save = sys.path
	sys.path = modelLocation	
	
	try:
		for model in __listModel:
			__model[model] = __import__(model)
	except:
		print "Can't load models"

	sys.path=save
	

def app(env, start_response):
	
	try:
		path = env['PATH_INFO']
	
		model = controller.parse(path)
		mod = __model[model]
		doModel = mod.doModel
		
		output = viewer.viewer(config.theme, config.language)
		doModel(env, output)
	except:
		#~ print name, error
		start_response('200 OK',[])
		import error
		return error.html
			
	start_response('200 OK', output.getHeader())
	
	return output.getBody()
	

__loadModels()

if __name__ == '__main__':
	# test unit, run without uwsgi and webserver

	env ={}
	env['PATH_INFO']='/view'
	env['QUERY_STRING']='id=3'
	def start_response(status, header):
		print "[Header]"
		print status
		print '&'.join(list(header))
		print "[Body]"
	
	print app(env, start_response)
	
else:
	# run with uwsgi and webserver
	
	import uwsgi
	uwsgi.applications = { '/':app}

